package com.zly.bscloud.service.impl;

import com.zly.bscloud.dto.SiteDTO;
import com.zly.bscloud.entity.Site;
import com.zly.bscloud.mapper.SiteMapper;
import com.zly.bscloud.service.SiteService;
import com.zly.bscloud.utils.entity.StatusCode;
import com.zly.bscloud.utils.exception.BpException;
import com.zly.bscloud.utils.utils.BeanHelper;
import com.zly.bscloud.utils.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @Author zhouxiaoyu
 * @Date 2020/5/26 21:22
 * @Version 1.0
 */
@Service
public class SiteServiceImpl implements SiteService {
    @Autowired
    private SiteMapper siteMapper;

    @Override
    @Transactional
    public SiteDTO saveSite(Site site){
        site.setId(UUIDUtils.UUID());

        //插入进数据库
        int count = siteMapper.insert(site);
        //只要不为1 则操作失败 抛出异常
        if (count != 1)
            throw new BpException(StatusCode.Failure);
        SiteDTO siteDTO = BeanHelper.copyProperties(site, SiteDTO.class);
        return siteDTO;
    }

    @Override
    @Transactional
    public List<SiteDTO> getSiteList(String user_id){
        // 创建Example
        Example example = new Example(Site.class);
        // 创建Criteria
        Example.Criteria criteria = example.createCriteria();
        // 添加条件
        criteria.andEqualTo("user_id", user_id);
        System.out.println(example);
        List<Site> siteList = siteMapper.selectByExample(example);
        //System.out.println(siteList);
        List<SiteDTO> siteDTOList = BeanHelper.copyWithCollection(siteList, SiteDTO.class);
        return siteDTOList;
    }

    @Override
    @Transactional
    public SiteDTO getSiteone(String id){

        Site site = siteMapper.selectByPrimaryKey(id);
        //System.out.println(siteList);
        SiteDTO siteDTO = BeanHelper.copyProperties(site, SiteDTO.class);
        return siteDTO;
    }
}
